from flask import Flask,session,g
import config
from exts import db,mail
from models import UserModel,EmailCaptchaModel
from blueprints.qa import bp as qa_bp
from blueprints.auth import bp as auth_bp
from flask_migrate import Migrate

app=Flask(__name__)
app.config.from_object(config)#绑定配置文件

db.init_app(app)#初始化
mail.init_app(app)

migrate=Migrate(app,db)

#注册蓝图
app.register_blueprint(qa_bp)
app.register_blueprint(auth_bp)

#hook 钩子函数 可以理解为拦截器
#before_request/before_first_request/after_request
@app.before_request
def my_before_request():
    user_id=session.get('user_id')#flask自动解密
    #print('user_id:',user_id)
    if user_id:
        user=UserModel.query.get(user_id)
        setattr(g,"user",user)#设置对象的值 g.user=user
    else:
        setattr(g,"user",None)#g.user=None
    #print('g:',g)
    #print('g.user=',g.user)

@app.context_processor#上下文处理器
def my_context_processor():
    #print('{"user":g.user}=',{"user":g.user})
    return {"user":g.user}

# @app.route('/')
# def main():
#     return '主页'

if __name__=='__main__':
    app.run(debug=True)